package com.ruoyi.pojo.tools;

import com.jnxx.basic.util.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.constants.ImageConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Slf4j
@Component
public class ImageTool {


    public AjaxResult uploadFile(MultipartFile uploadfile) {
        if (uploadfile.isEmpty()) {
            log.error("上传为空");
            throw new GlobalException("上传为空");
        }
        try {
            String path = saveUploadedFiles(uploadfile);
            return AjaxResult.success(path);
        } catch (IOException e) {
            log.error("上传错误"+e);
            e.printStackTrace();
            throw new GlobalException("上传错误");
        }
    }

    /**
     * 保存图片到本地
     * @param file
     * @return
     * @throws IOException
     */
    private String saveUploadedFiles(MultipartFile file) throws IOException {
        byte[] bytes = file.getBytes();
        long currentTimeMillis = System.currentTimeMillis();
        String originalFilename = file.getOriginalFilename();
        String newFileName = FilenameUtils.getBaseName(originalFilename) + ".jpg";
        Path path = Paths.get(ImageConstant.UPLOADED_FOLDER + currentTimeMillis + "-" + newFileName);
        Files.write(path, bytes);
        log.info("图片路径"+currentTimeMillis + "-" + newFileName);
        return currentTimeMillis + "-" + newFileName;
    }

    /**
     * 根据图片名称删除图片
     * @param productPictureName
     * @return
     */
    public AjaxResult delProductPicture(String productPictureName) {
        String path = ImageConstant.UPLOADED_FOLDER + productPictureName;
        File imageFile = new File(path);
        // 检查文件是否存在
        if (imageFile.exists()) {
            // 尝试删除文件
            if (imageFile.delete()) {
                System.out.println("Image deleted successfully.");
                return AjaxResult.success("图片删除成功!");
            } else {
                System.err.println("Failed to delete the image.");
                throw new GlobalException("图片删除错误");
            }
        } else {
            throw new GlobalException("图片不存在");
        }
    }

}
